<!-- 最后修改之前封装的组件 -->
<template>
  <div class="l-table">
    <!-- 只添加了el-popover这些代码 -->
    <div class="table-config">
      <div>
        <slot name="action"></slot>
      </div>
      <div >
        <export-btn v-if="export" :disabled="!multipleSelection.length"  :tableDatas="multipleSelection" :columns="columnsFilter"></export-btn>
        <template v-if="isSearch">
          <el-button type="primary" icon="search" @click="searchHandle">查询</el-button>
          <el-button icon="refresh" @click="searchReset">重置</el-button>
        </template>

        <el-popover v-if="showConfig" placement="bottom" :width="200" trigger="click" >
          <div class="check-all">
            <el-checkbox v-model="checkAll" :label="'全选'" />
          </div>
          <!-- <div v-for="(item, index) in currentColumns" :key="index">
            <el-checkbox v-model="item.show" :label="item.label" />
          </div> -->
          <el-tree
            ref="treeRef"
            style="max-width: 600px"
            :data="currentColumns"
            show-checkbox
            draggable
            node-key="prop"
            default-expand-all
            :expand-on-click-node="false"
            children="item"
            :allow-drop="allowDrop"
            :default-checked-keys="currentNodeKey"
            @check="setCurrentColumns"
            @node-drop="saveCurrentNodes"
            />
          <template #reference>
            <el-button title="列表筛选">
              <el-icon>
                <Setting />
              </el-icon>
            </el-button>
          </template>
        </el-popover>
      </div>

    </div>
    <!-- 表格 -->
    <el-table ref="tableRef" :data="tableData" border :max-height="maxHeight" style="width: 100%; overflow-y: scroll"
      v-loading="tableModule.loading" @selection-change="handleSelectionChange" :row-class-name="tableRowClassName"
      :cell-class-name="tableCellClassName" @cell-dblclick="cellDblClick" @row-dblclick="rowDblclick" table-layout="auto"
      scrollbar-always-on
      v-bind="tableProps">
      <el-table-column v-if="selection" type="selection" width="50" align="center"
        :selectable="(row, index) => selectableHandle(row, index)" />
      <!-- v-for 循环拿到了外层，在 el-table-column 判断 item.show 就可以了 -->
      <template v-for="(item, index) in columnsFilter">
        <el-table-column v-if="item.slot" :key="item.prop" :label="item.label" :prop="item.prop" :min-width="item.width"
          :width="item.fixedWidth" :align="item.align || 'left'" :sortable="sortable" :filters="hasfilter(item)"
          :filter-method="hasfilter(item) && filterHandler" v-bind="item.tableColumnProps || {}">

          <template #default="scope">
            <slot :name="item.slot" :row="scope.row" :tableindex="scope.$index" :column="item"></slot>
          </template>
        </el-table-column>
        <el-table-column v-else-if="item.show" :key="index" :prop="item.prop" :label="item.label"
          :align="item.align || 'left'" :min-width="item.width" :width="item.fixedWidth" :sortable="sortable"
          :filters="hasfilter(item)" :filter-method="hasfilter(item) && filterHandler"
          v-bind="item.tableColumnProps || {}">
          <template slot-scope="scope" #default="scope">
            <div v-if="scope.row.isSearch">

              <el-input @keyup.enter="searchHandle" v-model.trim="searchArr.filter(val => val.prop == item.prop)[0].value"
                v-if="searchArr.filter(val => val.prop == item.prop)[0]?.type == 'input'"
                :placeholder="item.placeholder || '请输入'" style="width: 100%" :clearable="item.clearable !== false" />
              <el-date-picker v-if="searchArr.filter(val => val.prop == item.prop)[0]?.type == 'datetimerange'"
                v-model="searchArr.filter(val => val.prop == item.prop)[0].value" type="daterange" style="width: 100%"
                range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DDTHH:mm:ssZ"
                :clearable="searchArr.filter(val => val.prop == item.prop)[0].clearable !== false"
                @keyup.enter="searchHandle" />
              <el-date-picker v-if="searchArr.filter(val => val.prop == item.prop)[0]?.type == 'date'"
                v-model="searchArr.filter(val => val.prop == item.prop)[0].value" type="date" style="width: 100%"
                placeholder="请选择" value-format="YYYY-MM-DD"
                :clearable="searchArr.filter(val => val.prop == item.prop)[0].clearable !== false"
                @keyup.enter="searchHandle" />
              <el-select v-if="searchArr.filter(val => val.prop == item.prop)[0]?.type == 'select'"
                v-model="searchArr.filter(val => val.prop == item.prop)[0].value" placeholder="请选择" style="width: 100%"
                :clearable="searchArr.filter(val => val.prop == item.prop)[0].clearable !== false"
                @keyup.enter="searchHandle">
                <el-option :label="it.label" :value="it.value"
                  v-for="it in searchArr.filter(val => val.prop == item.prop)[0].selectList"
                  :key="searchArr.filter(val => val.prop == item.prop)[0].value" />
              </el-select>
             
            </div>
            <div v-else-if="item.type == 'switch'">
              <el-switch v-model="scope.row[item.prop]" :active-value="item.activeValue"
                :inactive-value="item.inactiveValue" @change="props.tableModule.switchChange(scope.row)">
              </el-switch>
            </div>
            <div v-else-if="item.type == 'status'">
              <el-tag :type="item.color ? item.color[scope.row[item.prop]] : ''">{{
                props.tableModule.fieldChange(
                  scope.row[item.prop],
                  item.option
                )
              }}</el-tag>
            </div>
            <div v-else-if="item.type == 'image'">
              <el-image style="width: 60px; height: 60px" :src="scope.row[item.prop]"
                :preview-src-list="[scope.row[item.prop]]">
              </el-image>
            </div>
            <div v-else-if="item.type == 'time'">
              {{ formatDate(scope.row[item.prop]) }}
            </div>
            <div v-else-if="item.isEdit">
              <el-input v-model="scope.row[item.prop]" :placeholder="'请输入' + item.label" @blur="inputBlur(scope.row)"
                autofocus ref="inputRef" v-if="scope.row['index'] == rowIndex &&
                  scope.column['index'] == columnIndex
                  " />
              <div v-else>{{ scope.row[item.prop] }}</div>
            </div>
            <div v-else-if="item.prop == 'createUser'">
              <span v-if="scope.row.createdUser && scope.row.createdUser.nickName">
                {{scope.row.createdUser.nickName}}
              </span>
              <span v-else>{{scope.row.createUser}}</span>
              <!-- {{scope.row.createdUser?(scope.row.createdUser?.nickName):scope.row.createUser}} -->
            </div>
            <div v-else-if="item.prop == 'updateUser'">
              <!-- {{scope.row.updatedUser?.nickName}} -->
              <span v-if="scope.row.updatedUser && scope.row.updatedUser.nickName">
                {{scope.row.updatedUser.nickName}}
              </span>
              <span v-else>{{scope.row.updateUser}}</span>
            </div>

            <!-- <div v-else>{{ scope.row[item.prop] }}</div> -->
          </template>
        </el-table-column>
      </template>
      <slot name="event"></slot>
    </el-table>
    <div v-if="pagination && pages.total > 0" class="gva-pagination">
      <!-- <el-pagination layout="total, sizes, prev, pager, next, jumper" :current-page="pages.page"
        :page-size="pages.pageSize" :total="pages.total" :page-sizes="pageSizes" @current-change="changePages" /> -->
      <el-pagination
      layout="total, sizes, prev, pager, next, jumper"
      :current-page="pages.page"
      :page-size="pages.pageSize"
      :page-sizes="pageSizes"
      :total="pages.total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>
<script setup>
import { onMounted, computed, ref, watchEffect,getCurrentInstance,watch
 } from "vue";
import { getSbuDataList } from "@/api/confSbuData";
import exportBtn from "../exportBtn/exportBtn.vue";
import dayjs from "dayjs";

const tableRowClassName = ref("tableRowClassName");
const tableCellClassName = ref("tableCellClassName");
const emit = defineEmits(["updateMultipleSelection", "changePages", "rowDblclick", "onSubmit"]);

const props = defineProps({
  tableName: { type: String, default: "" },
  // elementui table props
  tableProps: { type: Object, default: () => { } },
  // 列
  columns: {
    type: Array,
    default: [],
  },
  // 表格数据
  tableData: {
    type: Array,
    default: [],
  },
  tableModule: {
    type: Object,
    default: {},
  },
  // 页码
  pages: {
    type: Object,
    default: () => ({ page: 1, pageSize: 20, total: 0 }),
  },
  // 分页页数筛选
  pageSizes: {
    type: Array,
    default: () => [10, 20, 30, 50, 100],
  },
  // 是否需要分页
  pagination: {
    type: Boolean,
    default: true,
  },
  // 是否开启勾选
  selection: {
    type: Boolean,
    default: true,
  },
  // 是否显示设置
  showConfig: {
    type: Boolean,
    default: true,
  },
  // 是否显示排序
  sortable: {
    type: Boolean,
    default: true,
  },
  maxHeight: {
    type: String,
    default: '100%'
  },
  searchArr: {
    type: Array,
    default: []
  },
  isSearch: {
    type: Boolean,
    default: false,
  },
  export:{
    type: Boolean,
    default: false,
  },
});

const { proxy } = getCurrentInstance();
const tableRef = ref(null);
setTimeout(() => {
  // 去除鼠标拖动列表左右滚动的效果
  // proxy?.$dragTable(tableRef)
}, 500);


// 多选数据
const multipleSelection = ref([]);

// 多选
const handleSelectionChange = (val) => {
  multipleSelection.value = val
  emit("updateMultipleSelection", val);
};

// 当前列
const currentColumns = ref([]);
// const currentColumns = computed(() => {
//     return props.columns || [];
// });

// 展示的列
const columnsFilter = computed(() => {
    return currentColumns.value.filter((item) => {
    return item.show;
    });
  
});

const treeRef = ref()

const currentNodeKey = computed(() => {
    const filterData = currentColumns.value.filter((item) => item.show)
    const d =  filterData.map(m => m.prop)
    console.log("d==========", d)
    return d
})

// 表头全选、反选
const checkAll = computed({
  get() {
    return currentColumns.value.every((item) => {
      return item.show == true;
    });
  },
  set(value) {
    console.log(value);
    currentColumns.value.forEach((item) => {
      item.show = value;
    });
      if (value) {
          currentNodeKey.value = currentColumns.value.map(m => m.prop)
          
      } else {
          currentNodeKey.value = []
      } 
      treeRef.value.setCheckedKeys(currentNodeKey.value)
      saveCurrentNodes()
  },
});

// 点击行
const cellDblClick = () => { };
// 双击行
const rowDblclick = (row, column) => {
  if (row.isSearch) {
    return
  }
  emit("rowDblclick", row)
};
currentColumns.value = props.columns;
const tableStorage = localStorage.getItem("tableStorage");
const tableStorageObj = JSON.parse(tableStorage) || {};
const tableStorageObjItem = tableStorageObj[props.tableName];
if (tableStorageObjItem && tableStorageObjItem.length > 0) {
    currentColumns.value = tableStorageObjItem
}

watchEffect(() => {
    if (!props.tableName) {
        currentColumns.value = props.columns;
    }
    if (props.isSearch) {
        if(!props.tableData[0]?.isSearch) {
        props.tableData.unshift({ isSearch: true })
        }
    }
});

// function changePages(page, pageSize) {
//   emit("changePages", { page, pageSize:20 });
// }
// 分页
const handleSizeChange = (val) => {
  // pageSize.value = val
  emit("changePages", { page:props.pages.page, pageSize:val });
}

// 修改页面容量
const handleCurrentChange = (val) => {
  // page.value = val
  emit("changePages", { page:val, pageSize:props.pages.pageSize });
}

/**
 *  filter 为 true 显示筛选框 filterFn 自定义过滤器 默认为prop的值
 *
 */
function hasfilter(column) {
  if (column.filter) {
    if (column.filterFn) return column.filterFn;
    else {
      const filters = [];
      const list = props.tableData.map((ptm) => {
        return { text: ptm[column.prop], value: ptm[column.prop] };
      });
      list.forEach((item) => {
        let index = filters.findIndex((v) => {
          return v.value == item.value;
        });
        if (index == -1) filters.push(item);
      });
      return filters;
    }
  } else return null;
}

// 过滤器
function filterHandler(value, row, column) {
  const property = column["property"];
  return row[property] === value;
}


const searchHandle = (obj) => {
  const queryArr = props.searchArr
  const queryParams = {};
  queryArr.map((m) => {
    queryParams[m.prop] = m.value;
  });
  if (queryParams['CreatedAt']) {
    queryParams["startCreatedAt"] = dayjs(queryParams.CreatedAt[0].substr(0,10)+'00:00:00').format('YYYY-MM-DDTHH:mm:ssZ') || "";
    queryParams["endCreatedAt"] = dayjs(queryParams.CreatedAt[1].substr(0,10)+'23:59:59').format('YYYY-MM-DDTHH:mm:ssZ') || "";
    console.log(  queryParams["startCreatedAt"], queryParams["endCreatedAt"] );
  }
  if (queryParams['UpdatedAt']) {
    queryParams["startUpdatedAt"] = dayjs(queryParams.UpdatedAt[0].substr(0,10)+'00:00:00').format('YYYY-MM-DDTHH:mm:ssZ') || "";
    queryParams["endUpdatedAt"] = dayjs(queryParams.UpdatedAt[1].substr(0,10)+'23:59:59').format('YYYY-MM-DDTHH:mm:ssZ') || "";
  }
  
  emit("onSubmit", queryParams);
}
const searchReset = (obj) => {
  props.searchArr.map((item) => {
    item.value = item.defaultValue || null;
  });
  emit("onSubmit", {});
}

function selectableHandle(row, index) {
  if (props.isSearch) {
    if (index == 0) {
      return false
    } else {
      return true
    }
  } else {
    return true
  }
}

// SBU的查询特殊处理
// 获取sbu列表
const getSbuData = async (keyword) => {
    await getSbuDataList({ page: 1, pageSize: 100, sbuName: keyword }).then(
        (res) => {
            if (res.code === 0) {
              let arr = []
                  res.data.list.map(item=>{
                    arr.push({
                      value:item.sbuName,
                      label:item.sbuName,
                    })
                });
              props.searchArr.forEach(item=>{
                if(item.prop=='sbuNum'||item.prop=='sbuName') {
                  item.type='select'
                  item.selectList=arr
                }
              })
            }
        }
    );
};

const allowDrop = (draggingNode, dropNode, type) => {
    if (type !== 'inner') return true
    else return false
}

const setCurrentColumns = (node, nodeInfo) => {
    console.log("rows========", node, nodeInfo)
    node.show = !node.show
    nodeInfo.checkedNodes = nodeInfo.checkedNodes.map(m => {
        if (m.prop === node.prop) {
            m.show = node.show
        }
        return m
    })
    // row.show = !row.show;
    columnsFilter.value = nodeInfo.checkedNodes
    saveCurrentNodes()
};

function saveCurrentNodes() {
    if (props.tableName) {
        const name = props.tableName
        const tableStorage = JSON.parse(localStorage.getItem('tableStorage')) || {}
        localStorage.setItem('tableStorage', JSON.stringify({
            ...tableStorage,
            [name]: currentColumns.value
        }))
    }
}

getSbuData()
</script>

<style lang="scss" scoped>
.table-config {
  display: flex;
  justify-content: space-between;
  margin-bottom: 1px;
}

.check-all {
  border-bottom: 1px solid #ccc5;
}

:deep(.el-pagination) {
  margin-top: 10px;
}
// .table-list{
  :deep(.el-scrollbar__view){
      padding-bottom: 10px;
  }
// }
</style>
<style lang="scss">
.table-header-search {
  padding: 0 !important;

  .table-header-search-body {
    padding: 10px;
  }

  .table-header-search-bottom {
    display: flex;
    border-top: 1px solid #ccc5;
    justify-content: space-around;
    padding: 6px;

    &>span {
      text-align: center;
      flex: 1;
      cursor: pointer;
    }

    &>span:nth-child(1) {
      border-right: 1px solid #ccc5;
    }
  }
}

.l-table {
  /* ---el-table滚动条公共样式--- */
.el-scrollbar {
  .el-scrollbar__bar{

  }
  // 横向滚动条
  .el-scrollbar__bar.is-horizontal{
    height: 10px;
    .el-scrollbar__thumb {
      opacity: 1; // 默认滚动条自带透明度
      // height: 10px !important; // 横向滑块的宽度
      border-radius: 5px; // 圆角度数
      // background-color: rgba(136, 219, 255, 1); // 滑块背景色
      background-color: #999;
      // box-shadow: 0 0 6px rgba(0, 0, 0, 0.15); // 滑块阴影
    }
  }
  .el-scrollbar__bar.is-vertical{
    width: 10px;
    .el-scrollbar__thumb {
      opacity: 1; // 默认滚动条自带透明度
      // height: 10px !important; // 横向滑块的宽度
      border-radius: 5px; // 圆角度数
      // background-color: rgba(136, 219, 255, 1); // 滑块背景色
      background-color: #999;
      // box-shadow: 0 0 6px rgba(0, 0, 0, 0.15); // 滑块阴影
    }
  }
  // .el-scrollbar__bar.is-horizontal {
  //   bottom: 8px;
  //   .el-scrollbar__thumb {
  //   opacity: 1; // 默认滚动条自带透明度
  //   // height: 10px !important; // 横向滑块的宽度
  //   border-radius: 2px; // 圆角度数
  //   // background-color: rgba(136, 219, 255, 1); // 滑块背景色
  //   background-color: var(--el-border-color-light);
  //   // box-shadow: 0 0 6px rgba(0, 0, 0, 0.15); // 滑块阴影
  // }
  // }
  // // 纵向滚动条
  // .el-scrollbar__bar.is-vertical {
  //   right: 10px;
  // .el-scrollbar__thumb {
  //   opacity: 1;
  //   width: 10px; // 纵向滑块的宽度
   
  //   border-radius: 2px;
  //   background-color: rgba(136, 219, 255, 1);
  //   box-shadow: 0 0 6px rgba(0, 0, 0, 0.15);
  // }  
  // }
  
}

.el-checkbox__inner {
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.el-checkbox__inner::after {
  left: 7px !important;
  top: 4px !important;
}
.el-checkbox__inner::before {
  top: 7px !important;
}
}


</style>
